#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
检查数据库状态和对话记录
"""

import sqlite3
import os

def check_database():
    """检查数据库状态"""
    # 检查多个可能的数据库路径
    db_paths = [
        'backend/data/ai_logging_engine.db',
        'backend/ai_logging_engine.db',
        'ai_logging_engine.db'
    ]
    
    db_path = None
    for path in db_paths:
        if os.path.exists(path):
            db_path = path
            break
    
    if not db_path:
        print("❌ 数据库文件不存在，检查的路径:")
        for path in db_paths:
            print(f"   - {path}")
        return
    
    print(f"✅ 数据库文件存在: {db_path}")
    
    try:
        conn = sqlite3.connect(db_path)
        cursor = conn.cursor()
        
        # 检查表结构
        cursor.execute("SELECT name FROM sqlite_master WHERE type='table'")
        tables = cursor.fetchall()
        print(f"\n📋 数据库表: {[t[0] for t in tables]}")
        
        # 检查工作区数据
        if 'workspaces' in [t[0] for t in tables]:
            cursor.execute("SELECT COUNT(*) FROM workspaces")
            workspace_count = cursor.fetchone()[0]
            print(f"🏢 工作区数量: {workspace_count}")
            
            if workspace_count > 0:
                cursor.execute("SELECT id, name, created_at FROM workspaces LIMIT 3")
                workspaces = cursor.fetchall()
                print("   工作区列表:")
                for ws in workspaces:
                    print(f"   - {ws[1]} (ID: {ws[0][:8]}...) 创建于: {ws[2]}")
        
        # 检查分析会话数据
        if 'analysis_sessions' in [t[0] for t in tables]:
            cursor.execute("SELECT COUNT(*) FROM analysis_sessions")
            session_count = cursor.fetchone()[0]
            print(f"📋 分析会话数量: {session_count}")
            
            if session_count > 0:
                cursor.execute("SELECT id, name, status, created_at FROM analysis_sessions LIMIT 3")
                sessions = cursor.fetchall()
                print("   会话列表:")
                for sess in sessions:
                    print(f"   - {sess[1]} (状态: {sess[2]}) 创建于: {sess[3]}")
        
        # 检查对话记录
        if 'conversations' in [t[0] for t in tables]:
            cursor.execute("SELECT COUNT(*) FROM conversations")
            conversation_count = cursor.fetchone()[0]
            print(f"💬 对话记录数量: {conversation_count}")
            
            if conversation_count > 0:
                cursor.execute("SELECT session_id, message_type, timestamp FROM conversations LIMIT 5")
                conversations = cursor.fetchall()
                print("   对话记录:")
                for conv in conversations:
                    print(f"   - 会话ID: {conv[0][:8]}... 类型: {conv[1]} 时间: {conv[2]}")
        else:
            print("❌ conversations表不存在 - 这可能是对话历史没有保存的原因")
        
        # 检查表结构
        if 'conversations' in [t[0] for t in tables]:
            cursor.execute("PRAGMA table_info(conversations)")
            columns = cursor.fetchall()
            print(f"\n📊 conversations表结构:")
            for col in columns:
                print(f"   - {col[1]} ({col[2]})")
        
        conn.close()
        
    except Exception as e:
        print(f"❌ 数据库检查失败: {e}")

if __name__ == "__main__":
    print("🔍 检查数据库状态...")
    print("=" * 50)
    check_database()
    print("=" * 50)
